package com.poker.duiued;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.util.Patterns;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.poker.iuious.yhyhjs.jklimj.User;
import com.poker.jkiuus.R;
import com.poker.jkiuus.uyrfgd.AppManager;
import com.poker.jkiuus.uyrfgd.DatabaseHelper;

import java.util.Objects;

public class UserAccount_InfoActivity extends AppCompatActivity {
    private User user = new User();
    private String userName;
    private DatabaseHelper databaseHelper;
    private TextView et_user_name;
    private EditText et_user_relName;
    private TextView et_user_email;
    private EditText et_user_phone;
    private Button btn_save_info;
    private String originalName;
    private String originalEmail;
    private String originalPhone;
    private String originalRelName;
    private Integer originalGender;
    private RadioGroup genderGroup;
    private Integer genderId = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.user_info_layout);
        AppManager.addActivity(this);

        databaseHelper = new DatabaseHelper(this);

        if (Build.VERSION.SDK_INT >= 33) {
            user = getIntent().getParcelableExtra("USER", User.class);
        } else {
            userName = getIntent().getStringExtra("USER_NAME");
            user = databaseHelper.queryUserByNameOrEmail(userName);
        }

        initView();

        et_user_email.setOnFocusChangeListener((v, hasFocus) -> {
            if (!hasFocus) {
                if (!isValidEmail(et_user_email.getText().toString())) {
                    et_user_email.setError("Invalid email address");
                }
            }
        });

        genderGroup.setOnCheckedChangeListener((group, checkedId) -> {

            if (checkedId == R.id.rb_male) {

                genderId = 0;
                System.out.println(genderId);
            } else if (checkedId == R.id.rb_female) {

                genderId = 1;
                System.out.println(genderId);
            } else if (checkedId == R.id.rb_unknown) {

                genderId = 2;
                System.out.println(genderId);
            }
        });
        btn_save_info.setOnClickListener(v -> saveInfo());
    }

    private void initView() {
        et_user_name = findViewById(R.id.et_user_name);
        et_user_relName = findViewById(R.id.et_user_relName);
        et_user_email = findViewById(R.id.et_user_email);
        et_user_email.setEnabled(false);
        et_user_phone = findViewById(R.id.et_user_phone);
        btn_save_info = findViewById(R.id.btn_save_info);
        genderGroup = findViewById(R.id.rg_gender);

        if (user != null) {
            originalName = user.getName();
            originalRelName = user.getRelName();
            originalEmail = user.getEmail();
            originalPhone = user.getPhone();
            originalGender = user.getGender();

            et_user_name.setText(originalName);
            et_user_name.setEnabled(false);
            et_user_name.setBackgroundColor(Color.TRANSPARENT);
            et_user_relName.setText(originalRelName);
            et_user_email.setText(originalEmail);
            et_user_phone.setText(originalPhone);

            switch (originalGender) {
                case 0:
                    genderGroup.check(R.id.rb_male);
                    genderId = 0;
                    break;
                case 1:
                    genderGroup.check(R.id.rb_female);
                    genderId = 1;
                    break;
                case 2:
                    genderGroup.check(R.id.rb_unknown);
                    genderId = 2;
                    break;
                default:
                    break;
            }
        }
    }

    private void saveInfo() {


        if (genderId == null) {
            showModifyDialog1("Please select a gender.");
            return;
        }

        String relName = et_user_relName.getText().toString().trim();
        String phone = et_user_phone.getText().toString().trim();
        String email = et_user_email.getText().toString().trim();

        User userByEmail = databaseHelper.selectUserByEmail(email);
        User userByPhone = databaseHelper.selectUserByPhone(phone);
        User userByName = databaseHelper.selectUserByName(user.getName());


        if ((email.equals(originalEmail) && phone.equals(originalPhone) && genderId.equals(originalGender))) {
            showModifyDialog1("No changes were made.");
        } else if (phone.length() <= 0 || email.length() <= 0 || relName.length() <= 0) {
            showModifyDialog1("Please don't leave it blank!");
        } else if (phone.length() < 7) {
            showModifyDialog1("The number of digits is too low!");
            et_user_phone.setError("The number of digits is too low!");
        } else if (phone.length() > 11) {
            showModifyDialog1("The number of digits is too long!");
            et_user_phone.setError("The number of digits is too long!");
        } else if (!isValidEmail(email)) {
            showModifyDialog1("Invalid email address!");
            et_user_email.setError("Invalid email address!");
        } else if (!Objects.equals(userByEmail.getId(), userByName.getId())) {
            showModifyDialog1("The email address already exists!");
            et_user_email.setError("The email address already exists!");
        } else if (userByPhone != null && !Objects.equals(userByPhone.getId(), userByName.getId())) {
            showModifyDialog1("The phone already exists!");
            et_user_phone.setError("The phone already exists!");
        } else {
            boolean b = databaseHelper.updateData(new User(originalName, phone, email, genderId, relName));
            if (b) {
                showModifyDialog2("Modification successful!", true);
            } else {
                showModifyDialog2("Failed to modify!Please try again later!", false);
            }
        }
    }

    private void showModifyDialog2(String message, boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("PROMPT");
        builder.setMessage(message);
        builder.setPositiveButton("OK", (dialog, which) -> {
            if (flag) {
                Intent intent = new Intent(this, UserAccountActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.putExtra("USER_NAME",user.getName());
                startActivity(intent);
                overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
            dialog.dismiss();
        }).setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private void showModifyDialog1(String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("PROMPT");
        builder.setMessage(message);
        builder.setPositiveButton("OK", (dialog, which) -> {
            dialog.dismiss();
        }).setCancelable(false);
        AlertDialog dialog = builder.create();
        dialog.show();
    }

    private boolean isValidEmail(String email) {
        return Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }
}
